﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon;

public class NetworkPickup : Photon.MonoBehaviour 
{

	private PhotonView photView;
	private Inventory invy;
	public PickUp associatedPickUP;
	public bool pickedUp = false;

	void Start () 
	{
		photView = PhotonView.Get (this); 
	}
	public void PickUp(Inventory senderInvy)
	{
		invy = senderInvy;
		if (!pickedUp)
		{
		photView.RPC ("PhotPickUp", PhotonTargets.AllViaServer);
		}
	}

	[PunRPC]
	public void PhotPickUp(PhotonMessageInfo info)
	{	
		if (this != null)
		{
			if (info.sender.IsLocal && !pickedUp)
			{	
				invy.Add (associatedPickUP.invyItem);
				pickedUp = true;
			}
			if (this.transform.gameObject.GetComponent<PhotonView> ().isMine)//for some reason only the photon view's "owner" can be the one to destroy the object
			{
				PhotonNetwork.Destroy (this.transform.gameObject.GetComponent<PhotonView> ());
			}
		}
	}
	void OnPhotonSerializeView(PhotonStream stream,PhotonMessageInfo info)
	{
		if (stream.isWriting)
		{	
			stream.SendNext (pickedUp);
		}else if (stream.isReading)
		{	
			pickedUp = (bool)stream.ReceiveNext ();
		}
	}
}
